import bcrypt from 'bcryptjs';
import jwt, { Secret } from 'jsonwebtoken';
import { AuthUser } from '../types/auth';
import { User } from '@prisma/client';
import { config } from '../config/env';

interface JwtSignOptions {
  expiresIn: string | number;
}

export async function hashPassword(password: string): Promise<string> {
  return bcrypt.hash(password, 10);
}

export async function comparePasswords(plainPassword: string, hashedPassword: string): Promise<boolean> {
  return bcrypt.compare(plainPassword, hashedPassword);
}

export function generateToken(user: AuthUser): string {
  const payload = {
    id: user.id,
    email: user.email,
    role: user.role
  };

  const secret: Secret = config.jwt.secret;
  const options: JwtSignOptions = {
    expiresIn: config.jwt.expiresIn || '24h'
  };

  return jwt.sign(payload, secret, options as jwt.SignOptions);
}

export function createAuthUser(user: User): AuthUser {
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const { password, ...authUser } = user;
  return authUser;
}

export function verifyToken(token: string): AuthUser {
  try {
    const secret: Secret = config.jwt.secret;
    const decoded = jwt.verify(token, secret) as AuthUser;
    return decoded;
  } catch (error) {
    throw new Error('Invalid token');
  }
}
